<?php
declare (strict_types=1);

namespace app\serviceapp;
use app\model\UserFavorite;
use app\MyException;
use app\util\CacheHelper;

/**
 * 收藏
 * Class UserFavoriteService
 * @package app\service
 */
class UserFavoriteService
{

    /**
     * 添加
     */
    public static function add($param)
    {
        $isExist = UserFavorite::where(['user_id' => $param['userId'], 'goods_id' => $param['goodsId']])->find();
        if (empty($isExist)) {
            $data = [];
            $data['user_id'] = $param['userId'];
            $data['goods_id'] = $param['goodsId'];
            $r =  UserFavorite::insert($data);
            if (!$r) {
                throw new MyException(10005);
            }
        } else {
            $goodsRedisKey = config('cachekeys.user_goods_id') . "COLLECT:" . $param['goodsId'] . ':' .  $param['userId'];
            $redis = new CacheHelper();
            $redis->del($goodsRedisKey);
            $r = UserFavorite::where(['user_id' => $param['userId'], 'goods_id' => $param['goodsId']])->delete();
            if (!$r) {
                throw new MyException(10005);
            }
        }
        return json_ok((object)[], 0);
    }
}
